#!/usr/bin/python

from mininet.net import Mininet
from mininet.node import RemoteController, CPULimitedHost
from mininet.cli import CLI
from mininet.util import dumpNodeConnections
from mininet.link import TCLink, Intf
import time
import sys
import topomodule

def run(topo, flow):
    "an auto scan"

    #build topo
    mytopo = topomodule.MyTopo(topo)
    Controller = RemoteController('c0', port = 6653)
    net = Mininet(topo = mytopo, controller = Controller, host=CPULimitedHost, link=TCLink, ipBase='192.168.3.64/27', autoSetMacs=True, autoStaticArp=True)
    #net = Mininet(topo = mytopo, host=CPULimitedHost, link=TCLink, autoSetMacs=True, autoStaticArp=True)
    #add Intf
    s1 = net.switches[0]
    Intf('eth1',node=s1)
    net.start()
    #net.pingAll()

    print('\033[1;34;40mDumping host connections\033[0m')
    dumpNodeConnections(net.hosts)
    time.sleep(2)
    
    print("\033[1;34;40mInsert rules\033[0m")
    with open(flow) as fin:
        numflow = int(fin.readline().split()[1])
        fin.readline()
        count = 0
        for line in fin.readlines():
            #print line
            switch = net.switches[int(line.split()[2].split("s")[1])-1]
            switch.cmdPrint(line.rstrip('\n'))
            count=count+1
        if (count == numflow):
            print("\033[1;34;40mInserted"),
            print(numflow),
            print(" preseted rules !\033[0m")
        else:
            print("\033[1;31;40mThe actual number of rules isn't accord with numRule.Please check the rule file.\033[0m")
            print("\033[1;34;40mInserted "),
            print(count),
            print(" preseted rules !\033[0m")
            
    time.sleep(1)
    CLI(net)
if __name__ =='__main__':
    print """\033[1;32;40m\n
    topology file: "/home/zxg/scandir-git/scandir/scantopo/testtopo.txt" 
    flowrule file: "/home/zxg/scandir-git/scandir/scantopo/rules/AclRule.txt\033[0m"""
    run("/home/zxg/scandir-git/scandir/scantopo/testtopo.txt", "/home/zxg/scandir-git/scandir/scantopo/rules/AclRule.txt")
